import { createRouter, createWebHistory } from 'vue-router/auto'
import { handleHotUpdate, routes } from 'vue-router/auto-routes'

import setPageTitle from "@/utils/set-page-title"
import type { EnhancedRouteLocation } from "@/router/types"
import useRouteCacheStore from '@/stores/routeCache'

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

NProgress.configure({ showSpinner: true, parent: '#app' })

const router = createRouter({
  history: createWebHistory(),
  routes,
})
if (import.meta.hot) handleHotUpdate(router)

router.beforeEach(async (to: EnhancedRouteLocation, _from, next) => {
  NProgress.start()

  const routeCacheStore = useRouteCacheStore()
  // Route cache
  routeCacheStore.addRoute(to)

  setPageTitle(to.meta.title)

  next()
})

router.afterEach(() => {
  NProgress.done()
})

export default router
